package com.ttloner.dao.impl;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author TTLoner
 * @date 2021/7/5 20:06
 * @description
 */
public class BaseDAO {
    //使用DbUtils操作数据库
    private QueryRunner qr=new QueryRunner();


    /*
     * @author: TTLoner
     * @time: 2021/7/6 10:41
     * @description:用于执行insert/update/Delete语句
     * @params: conn,sql,args
     * @return: 如果返回-1则执行失败，其余数字是指影响的行数
     */
    public int update(Connection conn,String sql,Object ...args){
        int update=-1;
        try {
            update = qr.update(conn, sql, args);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return update;
    }

    /*
     * @author: TTLoner
     * @time: 2021/7/5 20:51
     * @description:
     *查询返回一个javaBean的sql语句
     */
    public <T> T queryForOne(Connection conn,Class<T> clazz,String sql,Object ...args){
        try {
            T query = qr.query(conn, sql, new BeanHandler<T>(clazz), args);
            return query;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    /*
     * @author: TTLoner
     * @time: 2021/7/5 20:57
     * @description:
     *查询多条记录
     */
    public <T> List<T> queryForList(Connection conn, Class<T> clazz, String sql, Object ...args){
        try {
            List<T> query = qr.query(conn, sql, new BeanListHandler<T>(clazz), args);
            return query;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }


   public Object queryForSingleValue(Connection conn,String sql,Object ...args){
        try {
            Object query = qr.query(conn, sql, new ScalarHandler(), args);
            return query;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }
}
